package com.assets.Receive;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.Nullable;

import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;


import com.assets.Check.newTanWanCheck.BaseActivity1;
import com.assets.Ip_set.Url;
import com.assets.Listview_animation.BounceLoadingView;
import com.assets.R;
import com.assets.bean.Department_bean;
import com.assets.newNHF.util.LogUtils;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.User;
import com.assets.util.MyOkHttp;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Response;

/**
 * Created by Administrator on 2018/10/16.
 */

public class add_admin extends BaseActivity1 {

    private SearchView sv;
    private ListView lv;
    private List<String> X = new ArrayList<>();
    private List<String> p = new ArrayList<String>();
    private String url;
    private BounceLoadingView loadingView;
    private Object[] names;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_department);
        url = "http://" + Url.IP + "/api/adminQuery";
        //url = "http://192.168.1.159:8087/api/getAllPut";
        lv = (ListView) findViewById(R.id.lv_allot_sl);
        lv.setTextFilterEnabled(true);//设置lv可以被过虑
        sv = (SearchView) findViewById(R.id.tv_allot_sl);
        loadingView = (BounceLoadingView) findViewById(R.id.loadingView);
        loadingView.addBitmap(R.mipmap.v4);
        loadingView.addBitmap(R.mipmap.v5);
        loadingView.addBitmap(R.mipmap.v6);
        loadingView.addBitmap(R.mipmap.v7);
        loadingView.addBitmap(R.mipmap.v8);
        loadingView.addBitmap(R.mipmap.v9);
        loadingView.setShadowColor(Color.LTGRAY);
        loadingView.setDuration(700);
        loadingView.start();
        loadList();
        // 设置该SearchView默认是否自动缩小为图标
        sv.setIconifiedByDefault(false);
        sv.setQueryHint("查找");
        // 为该SearchView组件设置事件监听器
        // 设置该SearchView显示搜索按钮
        sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // 实际应用中应该在该方法内执行实际查询
                // 此处仅使用Toast显示用户输入的查询内容
                showToast("您的选择是:" + query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                Object[] obj = searchItem(newText);
                updateLayout(obj);
                return false;
            }
        });
        lv.setOnItemClickListener((adapterView, view, i, l) -> {
            String name = (String) adapterView.getItemAtPosition(i);//获取当前点击的item的字符串内容
            int position = X.indexOf(name);
            String id = p.get(position);
            LogUtils.d(name + "--" + id);
            Intent intent = new Intent();
            intent.putExtra("admin_name", name);
            intent.putExtra("admin_id", id);
            add_admin.this.setResult(7, intent);
            add_admin.this.finish();//把item的内容返回给之前的activity
        });
    }

    private void loadList() {
        String company = getIntent().getStringExtra("company_id");
        List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();

//        List<User> admins = new ArrayList<User>();
//        List<Dept> depts = deptService.likePids(Long.valueOf(companyId));

        List<User> users = MyDataBase.init(add_admin.this).userDao().getAllData();
        for(User user : users) {
            Map<String, Object> map = new HashMap<String, Object>();
            //判断用户部门是否相同
			/*if(user.getDeptId().equals(dept.getDeptId())) {
			}*/


            map.put("userId", user.getUserId());
            map.put("name", user.getName());
            maps.add(map);
        }

        showResponse(new Gson().toJson(maps));

        loadingView.setVisibility(View.GONE);
//        Map<String, String> map = new HashMap<>();
//        if (!TextUtils.isEmpty(company)){
//            map.put("companyId",company);
//            LogUtils.d(company);
//        }
//        MyOkHttp.getInstance().post(url, map, new MyOkHttp.requestMessage() {
//            @Override
//            public void requestFail() {
//                showToast("连接服务器失败");
//            }
//
//            @Override
//            public void requestComplete() {
//                runOnUiThread(() -> {
//                    loadingView.setVisibility(View.GONE);
//                });
//            }
//
//            @Override
//            public void requestSuccess(Response response) throws IOException {
//                String responseData = response.body().string();
//                LogUtils.d(responseData);
//                showResponse(responseData);
//            }
//        });
    }

    private void showResponse(final String responseData) {
        Gson gson = new Gson();
        List<Department_bean> userList = gson.fromJson(responseData, new TypeToken<List<Department_bean>>() {
        }.getType());
        for (int i = 0; i < userList.size(); i++) {
            X.add(userList.get(i).getName());
            p.add(userList.get(i).getId());
        }
        names = X.toArray();
        runOnUiThread(() -> {
            lv.setAdapter(new ArrayAdapter<Object>(getApplicationContext(),
                    R.layout.listview_style, names));
        });
    }

    public void updateLayout(Object[] obj) {
        lv.setAdapter(new ArrayAdapter<Object>(getApplicationContext(),
                R.layout.listview_style, obj));
    }

    public Object[] searchItem(String name) {
        ArrayList<String> mSearchList = new ArrayList<String>();
        for (int i = 0; i < X.size(); i++) {
            int index = X.get(i).indexOf(name);
            // 存在匹配的数据
            if (index != -1) {
                mSearchList.add(X.get(i));
            }
        }
        return mSearchList.toArray();
    }
}
